import { link } from 'fs';
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core';
import { Subscription } from 'rxjs';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { MessageService } from 'src/app/shared/service/message.service';
import { EventService } from 'src/app/shared/service/event.service';
import { AlertController, ModalController } from '@ionic/angular';
import { RemarksContentComponent } from '../remarks-content/remarks-content.component';
import { PageModalService } from 'src/app/shared/service/page-modal-service';

@Component({
  selector: 'app-recommend-choose',
  templateUrl: './recommend-choose.component.html',
  styleUrls: ['./recommend-choose.component.scss'],
})
export class RecommendChooseComponent implements OnInit {
  @Input() tagData: any;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  tempEvent: any;
  // 筛选及页面数据参数
  params: any = { content: {} };
  sessionId: string;
  moreSelect = false;
  recommendeIds: any;
  tempItem: any;
  listData: any;
  showLoadMore = false;
  constructor(
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private httpService: HttpService,
    private message: MessageService,
    private eventService: EventService,
    private ref: ChangeDetectorRef,
    public modalController: ModalController,
    private alertController: AlertController

  ) { }
  ngOnInit() {
    const listenerName = this.tagData.name + 'AskForList';
    this.eventService.eventEmit.on(listenerName, (obj) => {
      this.refreshListData(obj);
    });
    // 监听多选后的推荐
    if (this.eventService.eventEmit.listenerCount('recommendNow') > 0) {
      this.eventService.eventEmit.removeListener('recommendNow');
    }
    this.eventService.eventEmit.on('recommendNow', res => {

      const ids = [];
      this.listData.forEach(element => {
        if (element.checked) {
          ids.push(element[this.tagData.data.chooseSubmit.formKey]);
        }
      });
      if (ids.length > 0) {
        this.recommendeIds = ids.join(',');
        this.presentModal({
          minLength: 5,
          maxLength: 50,
          value: '',
          placeHolder: '请填写推荐说明，说明将展示给推荐客户',
          button: '确定'
        });

      }

    });
    // 监听多选后的推荐
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    this.eventService.eventEmit.on('auditNow', res => {

      const ids = [];
      let count = 0;

      let isMaxRow = false;
      // tslint:disable-next-line:prefer-for-of
      for (let index = 0; index < this.listData.length; index++) {
        const element = this.listData[index];
        if (element.checked) { // 蜂喔商户2.0新增
          if (this.tagData.data.chooseSubmit.type
            && this.tagData.data.chooseSubmit.type === 'ljpopup'
            && this.tagData.data.chooseSubmit.maxRow) {
            ++count;
            if (count > this.tagData.data.chooseSubmit.maxRow) {
              isMaxRow = true;
              this.appGlobalService.showToast('最多只能选择' + this.tagData.data.chooseSubmit.maxRow + '个', 2000, 'middle');
              break;
            }
          }
          ids.push(element[this.tagData.data.chooseSubmit.formKey]);

        }
      }
      if (!isMaxRow) {
        if (ids.length > 0) {
          this.moreSelect = true;
          this.recommendeIds = ids.join(',');
          if (res.content.idKey) {
            res.content[res.content.idKey] = this.recommendeIds;
          }
          this.submit(res);
        } else {
          this.recommendeIds = '';
        }
      }
    });

    // 全选
    this.eventService.eventEmit.on('recommendCheckedAll', res => {
      if (res) {
        this.listData.forEach(element => {
          element.checked = true;
        });
      } else {
        this.listData.forEach(element => {
          element.checked = false;
        });
      }
    });
    if (this.eventService.eventEmit.listenerCount('chooseAll') > 0) {
      this.eventService.eventEmit.removeListener('chooseAll');
    }
    this.eventService.eventEmit.on('chooseAll', res => {
      if (res) {
        this.listData.forEach(element => {
          element.checked = true;
        });
      } else {
        this.listData.forEach(element => {
          element.checked = false;
        });
      }
    });

    this.sessionId = localStorage.getItem('sessionId');
    if (this.tagData.data.submit !== undefined) {
      // 初始化参数
      this.params = this.tagData.data.submit;
      this.params.sessionId = this.sessionId;

      this.listData = this.tagData.data.data;
      this.pageSize = this.tagData.pageSize;
      this.pageTotal = this.tagData.pageTotal;

      this.showLoadMore =
        !this.tagData.data.moreButton &&
        this.tagData.data.submit &&
        this.pageTotal &&
        (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) &&
        this.tagData.asyncShow !== 'true';
    }
  }

  refreshListData(param) {
    const that = this;
    if (this.tempEvent) {
      this.tempEvent.target.disabled = false;
    }
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (!param.showName) {
      if (this.tagData.data.moreButton && this.tagData.data.moreButton.link.params.showName) {
        param.showName = this.tagData.data.moreButton.link.params.showName;
      } else if (this.tagData.data.submit && this.tagData.data.submit.content.showName) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    that.params.content = param;
    that.params.content.pageNo = this.pageNo;
    that.params.sessionId = localStorage.getItem('sessionId');
    this.httpService.post('application/submit', that.params, res => {
      if (res.success) {
        this.tagData.data.data = [];
        // const result = res.data.data; // JSON.parse(res.data.data);
        this.listData = res.data.data;
        if (res.data.submit) {
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }

        // this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;

        // tslint:disable-next-line:max-line-length
        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';
      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }
  // 单选 推荐
  recommentAction(item) {
    this.moreSelect = false;
    this.tempItem = item;
    this.recommendeIds = item[this.tagData.data.chooseSubmit.formKey];
    this.presentModal({ minLength: '5', maxLength: '50', value: '', placeHolder: '请填写推荐说明，说明将展示给推荐客户', button: '确定' });
  }

  recommentPhoneAction(phone) {
    // this.httpService.changeCallNumber(phone);
    this.presentAlertConfirm(phone);
  }

  async presentAlertConfirm(mobile) {
    const msg = mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });
    await alert.present();
  }

  goPage(item) {
    if (item) {
      this.pageModalService.openPage(item.link);
    }
  }

  async presentModal(textarea) {
    console.log("item", textarea);
    const modal = await this.modalController.create({
      showBackdrop: true,
      // backdropDismiss: false,
      cssClass: 'remarks',
      component: RemarksContentComponent,
      componentProps: { textarea, type: 'textarea' }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData, "moddddddd");
    if (!modalData.data) {
      return;
    }
    this.recommendWithRemark(modalData.data.value);
  }
  recommendWithRemark(value) {
    if (value.length < 1) {
      return;
    }
    const params = {
      sessionId: this.sessionId,
      content: this.tagData.data.chooseSubmit.content,
      id: this.tagData.data.chooseSubmit.id,
    };
    params.content[this.tagData.data.chooseSubmit.formKey] = this.recommendeIds;
    params.content.remark = value;
    this.httpService.post('application/submit', params, res => {
      if (res.success) {
        if (this.tagData.data.chooseSubmit.link && this.tagData.data.chooseSubmit.link.target.length > 0) {
          this.appGlobalService.openPage(this.tagData.data.chooseSubmit.link);
        } else {
          this.appGlobalService.showToast(res.message, 1500, 'middle');
          if (this.moreSelect) {
            this.listData.forEach(element => {
              if (element.checked) {
                element.fourthRowLeft.firstText.label = "刚刚已推荐";
              }
            });
          } else {
            this.tempItem.fourthRowLeft.firstText.label = "刚刚已推荐";
          }
        }

      } else {
        this.appGlobalService.showToast(res.message ? res.message : '推荐失败', 1500, 'middle');
        if (res.message && res.message === '推荐说明含有非法词') {
          this.presentModal({ minLength: 5, maxLength: 50, value, placeHolder: '请填写推荐说明，说明将展示给推荐客户', button: '确定' });
        }
      }

    });
  }

  choose(item) {
    item.checked = !item.checked;
    // 蜂喔赚钱宝1.7.1新增单选
    if (this.tagData.data.chooseSubmit && this.tagData.data.chooseSubmit.type && this.tagData.data.chooseSubmit.type === 'singleCheck') {
      this.listData.forEach(element => {
        if (item !== element) {
          element.checked = false;
        } else {
          // app - recommend - choose
          this.eventService.eventEmit.emit('recommendShareCheckList', item);
        }
      });
    } else {
      this.checkAll();
    }

  }
  // 检查是否已经全选
  checkAll() {
    // max 10
    if (this.tagData.data.chooseSubmit.type && this.tagData.data.chooseSubmit.type === 'ljpopup') {
      this.tagData.data.chooseSubmit.maxRow = this.tagData.data.chooseSubmit.maxRow > 0 ? this.tagData.data.chooseSubmit.maxRow : 10;
      let count = 0;
      const ids = [];
      this.listData.forEach(element => {
        if (element.checked) {
          ++count;
          if (count > this.tagData.data.chooseSubmit.maxRow) {
            element.checked = false;
            this.appGlobalService.showToast('最多只能选择' + this.tagData.data.chooseSubmit.maxRow + '个', 2000, 'middle');
          } else {
            if (this.tagData.data && this.tagData.data.chooseSubmit
              && this.tagData.data.chooseSubmit.content
              && this.tagData.data.chooseSubmit.content.changeStateThenCheck !== undefined) {
              if (element.serviceinfo_push_record_id) {
                ids.push(element.serviceinfo_push_record_id);
              } else
                if (element.id) {
                  ids.push(element.id);
                }
            }
          }
        }
      });
      // 1.7.1 赚钱宝 新增用于已推荐列表取消推荐
      this.eventService.eventEmit.emit('changeStateThenCheck', ids.length > 0 ? true : false);
      if (ids.length > 0) {
        // 蜂喔1.7.1 已推荐信息列表
        this.eventService.eventEmit.emit('alreadyRecommendAllResult', ids);
      }
    } else {

    }

    let all = true;
    this.listData.forEach(element => {
      if (!element.checked) {
        all = false;
      }
    });
    this.eventService.eventEmit.emit('recommendAllResult', all);


  }
  detailPage(link) {
    if (!link) {
      return;
    }
    this.pageModalService.openPage(link);
  }

  call(phone) {
    this.httpService.changeCallNumber(phone);
  }

  loadMoreData(event) {
    try {
      this.tempEvent = event;
      // // 请求下一个页面
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      // 请求获取新数据
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.listData.push(v);
            });
            this.checkAll();
          } else {
            event.target.disabled = true;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
      event.target.complete();

    }
  }

  doAction(item) {
    const params = {
      content: item.submit.content,
      id: item.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      this.appGlobalService.showToast(res.message, 1500, "middle");
      if (res.success) {
        if (item.link && item.link.target) {
          this.appGlobalService.openPage(item.link);
        } else {
          this.appGlobalService.reloadCurrentPage();
        }
      }
    });

  }

  submit(submit) {
    const params = {
      content: submit.content,
      id: submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.message) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
      if (res.success) {
        if (res.type === 'page' && res.target) {
          this.appGlobalService.openPage({ target: res.target, params: res.params, type: res.type });
        } else if (submit.back !== undefined) {
          const back = Math.abs(Number(submit.back));
          for (let index = 0; index < back; index++) {
            this.appGlobalService.popTarget();
          }
          this.eventService.eventEmit.emit("loadFooterComponent", []);
          this.appGlobalService.goBack(Number(submit.back));
        } else {
          this.appGlobalService.reloadCurrentPage();
        }
      } else {
        if (submit.back !== undefined) {
          const back = Math.abs(Number(submit.back));
          for (let index = 0; index < back; index++) {
            this.appGlobalService.popTarget();
          }
          this.eventService.eventEmit.emit("loadFooterComponent", []);
          this.appGlobalService.goBack(Number(submit.back));
        }
      }
    });

  }


  // tslint:disable-next-line:use-life-cycle-interface
  ngOnDestroy(): void {
    this.appGlobalService.tmpParams = undefined; // 赚钱宝1.7.1 指定分享推荐id跳转之后需要清空参数
    this.eventService.removeCustomListListenersByName('recommendShareCheckList');
    this.eventService.removeCustomListListenersByName('changeStateThenCheck');
    this.eventService.removeCustomListListenersByName(this.tagData.name + 'AskForList');
  }
}
